import {createBrowserHistory} from "../../history/createHistory";
import {createHooks, reactive} from "plain-design-composition";
import {iHistoryMeta} from "../../history/history.utils";

export const $nav = (() => {
  const history = createBrowserHistory({ base: __webpack_public_path__ });
  // const history = createHashHistory({ base: 'plain-ui' });

  const state = reactive({
    route: history.state.route,
  });

  const hooks = {
    onPathChange: createHooks<(meta: iHistoryMeta) => void>(),
    onHashChange: createHooks<(meta: iHistoryMeta) => void>(),
  };

  history.onPathChange((meta) => {
    if (meta.hash !== state.route.hash) {
      hooks.onHashChange.exec(meta);
    } else {
      hooks.onPathChange.exec(meta);
    }
    state.route = meta;
  });

  const setScrollTop = (top: number) => {
    document.documentElement.scrollTop = top;
  };
  const getScrollTop = () => {
    return document.documentElement.scrollTop;
  };

  return {
    history,
    state,
    setScrollTop,
    getScrollTop,
  };
})();
